package com.suneee.cloud.group.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suneee.base.util.ContextHelper;
import com.suneee.cloud.group.dao.DePartMentDao;
import com.suneee.cloud.group.dao.ShopAdminDao;
import com.suneee.cloud.group.entity.DePartMentEntity;
import com.suneee.cloud.group.entity.ShopAdminEntity;
import com.suneee.cloud.group.service.DePartMentService;
import com.suneee.context.page.Page;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.util.StringUtils;
import com.suneee.resources.ProductError;

@Service("api-department")
public class DePartMentServiceImpl implements DePartMentService 
{
	@Autowired
	private DePartMentDao dePartMentDao;
	
	@Autowired
	ShopAdminDao shopAdminDao ;
	
	
	@Override
	public Page<DePartMentEntity> queryDepartMentInfoPage(DePartMentEntity departEntity) {
		return dePartMentDao.queryDepartMentInfoPage(departEntity);
	}

	@Override
	public void insertDePartMentInfo(DePartMentEntity mentEntity) 
	{
		int level = 0;
		mentEntity.setName(mentEntity.getName());
		mentEntity.setDeptCode(mentEntity.getDeptCode());
		String enterPriseCode = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
		String userName = ContextHelper.getCurrentLoginInfo().getName();
		String childCode = mentEntity.getDeptCode();
		
		//判断添加几级账户组。 1，2，3
		if(StringUtils.isEmpty(mentEntity.getDeptCode()))
		{
			level = 1;
		}
		else
		{
			//根据传递的账号组编码长度判断添加几级账号组
			level = childCode.length()/2 + 1;
		}
		//当不传递 deptCode时表示添加1级账号组
		childCode= dePartMentDao.maxDepartCode(mentEntity.getDeptCode());
		
		//生成账号组编码
		childCode = this.createCode(childCode, level);
		mentEntity.setDeptCode(childCode);

		//判断 账号组名称是否存在
		boolean isExit = dePartMentDao.isExitsInDPartName(mentEntity);
		if(isExit)
		{
			throw ErrorUtils.wrap(ProductError.ACOUNT_IS_EIXT_NAME);
		}
		Date date = new Date();
		mentEntity.setCreateTime(date);
		mentEntity.setUpdateTime(date);
		mentEntity.setEnterpriseCode(enterPriseCode);
		mentEntity.setCreateUser(userName);
		mentEntity.setUpdateUser(userName);
		if(null == mentEntity.getEnabled())
		{
			mentEntity.setEnabled(1);
		}
		dePartMentDao.insertDePartMentInfo(mentEntity);
	}
	
	

	@Override
	public void updateDePartMentInfo(DePartMentEntity departEntity) 
	{
		Assert.notNull(departEntity, "账号组对象");
		Assert.notNull(departEntity.getDeptCode(), "账号组编码");
        Assert.notEmpty(departEntity.getName(), "账号组名称");
		//判断 账号组名称是否存在
		boolean isExit = dePartMentDao.isExitsUpDPartName(departEntity);
		if(isExit)
		{
			throw ErrorUtils.wrap(ProductError.ACOUNT_IS_EIXT_NAME);
		}
		String enterPriseCode = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
		String userName = ContextHelper.getCurrentLoginInfo().getAccount();
		departEntity.setEnterpriseCode(enterPriseCode);
		departEntity.setUpdateUser(userName);
		dePartMentDao.updateDePartMentInfo(departEntity);
	}

	@Override
	public void deleteDePartMentInfo(DePartMentEntity departEntity) 
	{
		Assert.notNull(departEntity, "账号组对象不能为空");
		Assert.notNull(departEntity.getDeptCode(), "账号组编码不能为空");
		//判断账号组是否被使用/或是否存在子账号组
		boolean flag = dePartMentDao.isExitsdPartFlag(departEntity);
		if(flag)
		{
			throw ErrorUtils.wrap(ProductError.ACOUNT_IS_NOT_DELETE);
		}
		String enterPriseCode = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
		departEntity.setEnterpriseCode(enterPriseCode);
		dePartMentDao.deleteDePartMentInfo(departEntity);
	}

	@Override
	public List<DePartMentEntity> queryDePartMentList() 
	{
		List<DePartMentEntity> oneList = dePartMentDao.queryDePartMentList(2,null);
		if(null != oneList && oneList.size() > 0)
		{
			/**
			 * 拼装树结构 账号数据列表
			 */
			//一级账号组
			for(DePartMentEntity oneMent:oneList)
			{
				oneMent.setLevel(1);
				List<DePartMentEntity> twoList = dePartMentDao.queryDePartMentList(4,oneMent.getDeptCode());
				
				//二级账号组
				if(null != twoList && twoList.size() > 0)
				{
					for(DePartMentEntity twoMent:twoList)
					{
						twoMent.setLevel(2);
						//三级账号组
						List<DePartMentEntity> threeList = dePartMentDao.queryDePartMentList(6,twoMent.getDeptCode());
						if(null != threeList && threeList.size() > 0)
						{
							for(DePartMentEntity threeMent:threeList)
							{
								threeMent.setLevel(3);
								//四级账号组
								List<DePartMentEntity> fourList = dePartMentDao.queryDePartMentList(8,threeMent.getDeptCode());
								if(null != fourList && fourList.size() > 0)
								{
									for(DePartMentEntity fourMent:fourList)
									{
										fourMent.setLevel(4);
										//5级账号组
										List<DePartMentEntity> fiveList = dePartMentDao.queryDePartMentList(10,fourMent.getDeptCode());
										if(null != fiveList && fiveList.size() > 0)
										{
											for(DePartMentEntity fiveMent:fiveList)
											{
												fiveMent.setLevel(5);
												//6级账号组
												List<DePartMentEntity> sixList = dePartMentDao.queryDePartMentList(12,fiveMent.getDeptCode());
												if(null != sixList && sixList.size() > 0)
												{
													for(DePartMentEntity sixMent:sixList)
													{
														sixMent.setLevel(6);
													}
													fiveMent.setChildren(sixList);
												}
											}
											fourMent.setChildren(fiveList);
										}
									}
									threeMent.setChildren(fourList);
								}
								
							}
							twoMent.setChildren(threeList);
						}
					}
					oneMent.setChildren(twoList);
				}
				
			}	
		}
		
		
		return oneList;
	}
	
	
	// 创建新的编码
	public String createCode(String maxCode, int level)
	{
			String CODE_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			if (maxCode == null || maxCode.length() == 0) {
				return "01";
			}
			int f1 = 0;
			int f2 = -1;
			String ret;
			String superCode = maxCode;
			if (maxCode.length() >= level * 2) {
				superCode = maxCode.substring(0, (level - 1) * 2);
				String curChild = maxCode.substring((level - 1) * 2);
				f1 = CODE_CHARS.indexOf(curChild.charAt(0));
				f2 = CODE_CHARS.indexOf(curChild.charAt(1));

			} else {
				superCode = maxCode.substring(0, (level - 1) * 2);
			}
			f2++;
			if (f2 == CODE_CHARS.length()) {
				f1++;
				f2 = 0;
				if (f1 == CODE_CHARS.length()) {
					throw ErrorUtils.wrap(ProductError.CODING_IS_NOT_ENOUGH);
				}
			}
			ret = superCode + CODE_CHARS.charAt(f1) + CODE_CHARS.charAt(f2);

			return ret;

		}

	@Override
	public List<Map<String,Object>> getDeptNameList(String deptCode) 
	{
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
		Object [] args = new Object[1];
		args[0] = enterpriseCode;
		List<Map<String,Object>> oneList = dePartMentDao.queryForList("select dept_code as deptCode ,name from t_department where length(dept_code) = 2 and enterprise_code = ?", args);
		if(null != oneList && oneList.size() > 0)
		{
			/**
			 * 拼装树结构 账号数据列表
			 */
			//一级账号组
			for(Map<String,Object> oneMent:oneList)
			{
				if(!StringUtils.isEmpty(deptCode) &&deptCode.equals(oneMent.get("deptCode")))
				{
					oneMent.put("selected", "true");
				}
				else
				{
					oneMent.put("selected", "false");
				}
				Object [] args2 = new Object[2];
				args2[0] = oneMent.get("deptCode")+"%";
				args2[1] = enterpriseCode;
				List<Map<String,Object>> twoList = dePartMentDao.queryForList("select dept_code as deptCode ,name from t_department where length(dept_code) = 4 and dept_code like ? and enterprise_code = ?",args2);
				//二级账号组
				if(null != twoList && twoList.size() > 0)
				{
					for(Map<String,Object> twoMent:twoList)
					{
						if(!StringUtils.isEmpty(deptCode) &&deptCode.equals(twoMent.get("deptCode")))
						{
							twoMent.put("selected", "true");
						}
						else
						{
							twoMent.put("selected", "false");
						}
						//三级账号组
						Object [] args3 = new Object[2];
						args3[0] = twoMent.get("deptCode")+"%";
						args3[1] = enterpriseCode;
						List<Map<String,Object>> threeList = dePartMentDao.queryForList("select dept_code as deptCode ,name from t_department where length(dept_code) = 6 and dept_code like ? and enterprise_code = ? ",args3);
						if(null != threeList && threeList.size() > 0)
						{
							for(Map<String,Object> threeMent:threeList)
							{
								if(!StringUtils.isEmpty(deptCode) &&deptCode.equals(threeMent.get("deptCode")))
								{
									threeMent.put("selected", "true");
								}
								else
								{
									threeMent.put("selected", "false");
								}
								//四级账号组
								Object [] args4 = new Object[2];
								args4[0] = threeMent.get("deptCode")+"%";
								args4[1] = enterpriseCode;
								List<Map<String,Object>> fourList = dePartMentDao.queryForList("select dept_code as deptCode ,name from t_department where length(dept_code) = 8 and dept_code like ? and enterprise_code = ? ",args4);
								if(null != fourList && fourList.size() > 0)
								{
									for(Map<String,Object> fourMent:fourList)
									{
										if(!StringUtils.isEmpty(deptCode) &&deptCode.equals(fourMent.get("deptCode")))
										{
											fourMent.put("selected", "true");
										}
										else
										{
											fourMent.put("selected", "false");
										}
										//5级账号组
										Object [] args5 = new Object[2];
										args5[0] = fourMent.get("deptCode")+"%";
										args5[1] = enterpriseCode;
										List<Map<String,Object>> fiveList = dePartMentDao.queryForList("select dept_code as deptCode ,name from t_department where length(dept_code) = 10 and dept_code like ? and enterprise_code = ? ",args5);
										if(null != fiveList && fiveList.size() > 0)
										{
											for(Map<String,Object> fiveMent:fiveList)
											{
												if(!StringUtils.isEmpty(deptCode) &&deptCode.equals(fiveMent.get("deptCode")))
												{
													fiveMent.put("selected", "true");
												}
												else
												{
													fiveMent.put("selected", "false");
												}
												//6级账号组
												Object [] args6 = new Object[2];
												args6[0] = fiveMent.get("deptCode")+"%";
												args6[1] = enterpriseCode;
												List<Map<String,Object>> sixList = dePartMentDao.queryForList("select dept_code as deptCode ,name from t_department where length(dept_code) = 12 and dept_code like ? and enterprise_code = ? ",args6);
												if(null != sixList && sixList.size() > 0)
												{
													fiveMent.put("children",sixList);
												}
											}
											fourMent.put("children",fiveList);
										}
									}
									threeMent.put("children",fourList);
								}
								
							}
							twoMent.put("children",threeList);
						}
					}
					oneMent.put("children",twoList);
				}
				
			}	
		}
		 return oneList;
	}

	@Override
	public List<Map<String, Object>> getDeptUnPermssion(String deptCode,String name,String shopId) 
	{
	//	Assert.notNull(deptCode, "账号组编码");
		Assert.notNull(shopId, "店铺编码");
		String sql = "";
		List<Map<String,Object>> resutList = null;
		if(StringUtils.isEmpty(name) && StringUtils.isEmpty(deptCode))
		{
			Object [] arg2 = new Object[1];
			arg2[0] = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
			//sql = "SELECT admin_id adminId,dept_code deptCode,name FROM t_administrator   WHERE dept_code = ? AND name like ? AND admin_id not in (SELECT admin_id FROM t_shop_admin where shop_id = ?)";
			sql = "SELECT admin_id adminId,dept_code deptCode,name FROM t_administrator  where enabled = 1 and admin = 0 and dept_code is not null  and enterprise_code = ?";
			resutList = dePartMentDao.queryForList(sql, arg2 );
		}
		else if(StringUtils.isEmpty(name) && !StringUtils.isEmpty(deptCode))
		{
			Object [] arg1 = new Object[3];
			arg1[0] = deptCode;
			arg1[1] = shopId;
			arg1[2] = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
			sql = "SELECT admin_id as adminId,dept_code as deptCode,name FROM t_administrator   WHERE  enabled = 1 and admin = 0 and dept_code = ? AND  admin_id not in (SELECT admin_id FROM t_shop_admin where shop_id = ?)  and enterprise_code = ?";
			resutList = dePartMentDao.queryForList(sql, arg1);
		}
		else
		{
			Object [] arg2 = new Object[4];
			name = "%" + name + "%";
			arg2[0] = deptCode;
			arg2[1] = name;
			arg2[2] = shopId;
			arg2[3] = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
			sql = "SELECT admin_id adminId,dept_code deptCode,name FROM t_administrator   WHERE  enabled = 1 and admin = 0 and dept_code = ? AND name like ? AND admin_id not in (SELECT admin_id FROM t_shop_admin where shop_id = ?)  and enterprise_code = ?";
			resutList = dePartMentDao.queryForList(sql, arg2 );
		}
		return resutList;
	}

	@Override
	public List<Map<String, Object>> getDeptPermssion(String deptCode,String name,String shopId) 
	{
		Assert.notNull(shopId, "店铺编码");
		String sql = "";
		List<Map<String,Object>> resutList = null;
		if(StringUtils.isEmpty(name))
		{
			Object [] arg1 = new Object[2];
			arg1[0] = shopId;
			arg1[1] = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
			sql = "SELECT admin_id as adminId,dept_code as deptCode,name FROM t_administrator WHERE  enabled = 1 and admin = 0 and admin_id in (SELECT admin_id FROM t_shop_admin where shop_id = ?) and enterprise_code = ?";
			resutList = dePartMentDao.queryForList(sql, arg1);
		}
		else
		{
			Object [] arg2 = new Object[3];
			name = "%" + name + "%";
			arg2[0] = name;
			arg2[1] = shopId;
			arg2[2] = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
			sql = "SELECT admin_id adminId,dept_code deptCode,name FROM t_administrator   WHERE  enabled = 1 and admin = 0 and name like ? AND admin_id in (SELECT admin_id FROM t_shop_admin where shop_id = ?)  and enterprise_code = ?";
			resutList = dePartMentDao.queryForList(sql, arg2 );
		}
		return resutList;
	}

	@Override
	public void insertadminRoleInfo(String shopId,List<ShopAdminEntity> checkList) 
	{
		Assert.notNull(shopId, "店铺编码");
		String enterPriseCode = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
		if(null == checkList || checkList.size() == 0)
		{
			Object [] args = new Object[2];
			args[0] = shopId;
			args[1] = enterPriseCode;
			shopAdminDao.deleteWhere("shop_id = ? and admin_id != (SELECT admin_id FROM t_administrator  WHERE enterprise_code = ? AND admin = 1)", args);
		}
		else
		{
			for(ShopAdminEntity shopAdmin:checkList)
			{
				if(null != shopAdmin)
				{
					shopAdmin.setShopId(shopId);
				}
			}
			shopAdminDao.insertShopAdminInfo(checkList);	
		}
		
		//获取当前登录用户所属企业的超级管理员id
		List<Map<String,Object>> adminList = shopAdminDao.queryForList("select admin_id from t_administrator where enterprise_code = ? and admin = 1", enterPriseCode);
		String adminId = ContextHelper.getCurrentLoginInfo().getAdminId()+"";
		Object [] args1 = new Object[2];
		args1[0] = adminId;
		args1[1] = shopId;
		
		//判断是否已经存在该授权。
		List<ShopAdminEntity>  resultFlag =shopAdminDao.selectWhere(" admin_id = ? and shop_id = ? ", args1);
		
		//若当前的登录用户不是超级管理员。 则需要赋予当前登录者的角色授权
		if(!adminId.equals(adminList.get(0).get("admin_id")) && (null == resultFlag || resultFlag.size() ==0))
		{
			shopAdminDao.inserSuperAdminfinfo(shopId + "", adminId);
		}
		
	}

}
